<?php

namespace Dcat\Admin\GridCategory\Grid\Tools;

use Dcat\Admin\Grid;
use Dcat\Admin\Support\Helper;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Dcat\Admin\Widgets\Tree;

class CategoryTree extends Tree
{
    /**
     * @var Grid
     */
    protected $grid;
    protected $view = 'chinahacker.grid-category::tree';
    /**
     * @var Request
     */
    protected $request;

    /**
     * @var array|Collection
     */
    protected $tree = [];

    /**
     * @var array
     */
    protected $selected;

    /**
     * @var string
     */
    protected $queryNameSuffix = '_selector';

    public $column;
    /**
     * Selector constructor.
     */

    public function __construct(Grid $grid)
    {
        $this->grid = $grid;
        $this->request = request();
    }

    public function treeNodes($nodes, $column = 'category_')
    {
        $this->tree = new Collection();
        $this->tree[$column] =  $nodes;
        $this->column = $column;
        // $this->tree = $nodes;
        parent::__construct($nodes);
    }
    public function render()
    {
        $this->id($this->id);
        $this->class('jstree-wrapper');
        $this->defaultHtmlAttribute('style', 'border:0;padding:5px 0');

        $this->formatNodes();

        $this->variables = [
            'id'    => $this->id,
            'nodes' => &$this->nodes,
            'column' => &$this->column,
        ];

        static::requireAssets();

        $this->class($this->getElementClass(), true);

        $html = $this->html();

        $this->withScript();

        return $html; // TODO: Change the autogenerated stub
    }
    /**
     * @return string
     */
    public function getQueryName()
    {
        return $this->grid->makeName($this->queryNameSuffix);
    }

    /**
     * Get all tree.
     *
     * @param bool $formatKey
     *
     * @return array|Collection
     */
    public function all(bool $formatKey = false)
    {
        if ($formatKey) {
            return $this->tree->mapWithKeys(function ($v, $k) {
                return [$this->formatKey($k) => $v];
            });
        }

        return $this->tree;
    }



    public function formatKey($column)
    {
        return str_replace('.', '_', $column);
    }
    /**
     * @return array
     */
    public function parseSelected()
    {
        if (!is_null($this->selected)) {
            return $this->selected;
        }

        $selected = $this->request->get($this->getQueryName(), []);
        if (!is_array($selected)) {
            return [];
        }

        $selected = array_filter($selected, function ($value) {
            return !is_null($value);
        });

        foreach ($selected as &$value) {
            $value = explode(',', $value);

            foreach ($value as &$v) {
                $v = (string) $v;
            }
        }

        return $this->selected = $selected;
    }

    protected function formatNodes()
    {


        if (!$this->nodes) {
            return;
        }

        $idColumn = $this->columnNames['id'];
        $textColumn = $this->columnNames['text'];
        $parentColumn = $this->columnNames['parent'];

        $nodes = [];

        foreach ($this->nodes as $k => &$v) {
            if (empty($v[$idColumn])) {
                continue;
            }

            $parentId = $v[$parentColumn] ?? '#';
            if (empty($parentId)) {
                $parentId = '#';
            }

            $v['state'] = [];
            $selected = $this->parseSelected();;
            if ($this->checkAll || ($selected && in_array($v[$idColumn], $selected[$this->column]))) {
                $v['state']['selected'] = true;
            }


            $v['state']['disabled'] = false;
            $v['state']['url'] =  $this->url(0);

            $nodes[] = [
                'id'     => $v[$idColumn],
                'text'   => $v[$textColumn] ?? null,
                'parent' => $parentId,
                'state'  => $v['state'],

            ];
        }

        $this->nodes = &$nodes;
    }
}
